<template>
  <div class="shopping-cart">
    <v-navbar :edit="text" @edit="_ShoppingEdit"></v-navbar>
    <div class="shopping-wrapper">
      <div class="shopping-item" v-for="(item, index) in foodData" :key="item.id" v-if="foodData">
        <div class="shopping-head">
          <div class="sh-left">
            <check-box class="sh-icon" :check="item.check" @clickBtn="_checkShop(index)"/>
            <span class="name">{{item.shopName}}</span>
          </div>
          <!--<div class="sh-right">{{item.shopName}}</div>-->
        </div>
        <ul class="sh-list">
          <li class="l-item" v-for="(food, i) in item.foods" :key="food.id">
            <div class="l-check">
              <check-box :check="food.sonCheck" @clickBtn="_checkFoods(index, i)"/>
            </div>
            <div class="l-img">
              <img :src="food.goodsLogo" width="64" height="80" alt="">
            </div>
            <div class="l-desc">
              <div class="l-name">{{food.goodsName}}</div>
              <div class="num">
                <span class="price">￥{{food.platformRetailPrice}}</span>
                <add-delete :num="food.goodsCount" @add="_Add($event, index, i)" @minus="_Minus($event, index, i)"/>
              </div>
            </div>
          </li>
        </ul>
      </div>
      <div class="cartNull" v-if="cartList">
        <Icon type="md-cart" class="cart-iocn" />
        购物车是空的~~~~
      </div>
    </div>
    <div class="shopping-bottom" v-if="!cartList">
      <div class="shopping-select">
        <div class="left">
          <check-box class="sh-icon" :check="checkAll" @clickBtn="_AllCheck"/>
          <span>全选</span>
        </div>
        <div class="right" v-if="edit">
          <span class="text">合计:</span>
          <span class="price">￥{{total}}</span>
        </div>
        <div class="right deleted" v-else>
          <div class="delete" @click="_empty">清空</div>
          <div class="delete" @click="_delete">删除</div>
        </div>
      </div>
      <div class="shopping-balance" v-if="edit" @click="_goOrder">
        去结算
      </div>
    </div>
  </div>
</template>

<script>
  import navbar from '@c/navbar/navbar'
  import CheckBox from '@c/CheckBox/CheckBox'
  import AddDelete from '@c/AddDelete/AddDelete'
  import { mapState, mapMutations } from 'vuex'
  import { MessageBox } from 'mint-ui'
  import { tokenPost, jtpost, gtpost, tokenLink, jtget } from '@api/axiosByToken'

  export default {
    name: 'ShoppingCart',
    data() {
      return {
        text: '编辑',
        foodData: [],
        checkAll: false,
        total: 0,
        edit: true,
        cartList: true
      }
    },
    components: {
      'v-navbar': navbar,
      CheckBox,
      AddDelete,
    },
    computed: {
      ...mapState(['wtitle', 'rback']),
      _countTotal() {
        let count = 0
        let len = []
        this.foodData.forEach(item => {
          len = item.foods.filter(i => {
            return i.sonCheck === true
          })
          len.forEach(item => {
            count += item.goodsCount * item.platformRetailPrice
          })
        })
        this.total = count
      },
    },
    methods: {
      ...mapMutations(['WTITLE', 'RBACK', 'REVISE', 'LOADDING']),
      //编辑
      _ShoppingEdit() {
        this.edit = !this.edit
        if (this.edit) {
          this.text = '编辑'
        } else {
          this.text = '完成'
        }
      },
      //选择商品
      _checkFoods(food, i) {
        this.foodData[food].foods[i].sonCheck = !this.foodData[food].foods[
          i
          ].sonCheck
        let len = this.foodData[food].foods.filter(f => {
          return f.sonCheck === true
        })
        if (len.length === this.foodData[food].foods.length) {
          this.foodData[food].check = true
          this._doAllCheck()
        } else {
          this.foodData[food].check = false
          this._doAllCheck()
        }
      },
      //选择店铺
      _checkShop(index) {
        this.foodData[index].check = !this.foodData[index].check
        this.foodData[index].foods.forEach(item => {
          item.sonCheck = this.foodData[index].check
        })
        this._doAllCheck()
      },
      //判断是否全选
      _doAllCheck() {
        let len = this.foodData.filter(item => {
          return item.check === true
        })
        if (len.length === this.foodData.length) {
          this.checkAll = true
        } else {
          this.checkAll = false
        }
      },
      //全选
      _AllCheck() {
        this.checkAll = !this.checkAll
        this.foodData.forEach(item => {
          item.check = this.checkAll
          item.foods.forEach(i => {
            i.sonCheck = this.checkAll
          })
        })
        console.log(this.foodData)
      },
      //加
      _Add(val, food, i) {
        this.foodData[food].foods[i].goodsCount = val
        this._sendShoppingCount(this.foodData[food].foods[i].id, this.foodData[food].foods[i].goodsCount)
      },
      //减
      _Minus(val, food, i) {
        this.foodData[food].foods[i].goodsCount = val
        this._sendShoppingCount(this.foodData[food].foods[i].id, this.foodData[food].foods[i].goodsCount)
      },
      //添加数据发送到后台
      _sendShoppingCount(id, count) {
        let info = {
          userId: window.localStorage.getItem('userId'),
          id: id,
          goodsCount: count
        }
        tokenPost(tokenLink.cart.updateNum, info).then(re => {
          if(re.status === 0) {

          } else {

          }
        })
      },
      //清空
      _empty() {
        let info = {
          userId: window.localStorage.getItem('userId')
        }
        MessageBox({
          title: '',
          message: '您是否要清空购物车？',
          showCancelButton: true,
        }).then(action => {
          if (action == 'confirm') {
            this.$store.state.loadding = true
            tokenPost(tokenLink.cart.empty, info).then(re => {
              this.$store.state.loadding = false
              if (re.status === 0) {
                this.$Message.success('清空成功')
                this._checkShoppingCart()
              } else {
                this.$Message.error(re.msg)
              }
            })
          }
        })
      },
      //删除
      _delete() {
        let count = this._getGoods()
        if (count.length === 0) {
          this.$Message.info('请选择要删除的商品')
          return
        }
        let ids = []
        count.forEach(item => {
          ids.push(item.id)
        })
        let info = {
          userId: window.localStorage.getItem('userId'),
            ids: ids.join(",")
        }
        MessageBox({
          title: '',
          message: `确定要删除这${count.length}种商品吗？`,
          showCancelButton: true,
        }).then(action => {
          if (action == 'confirm') {
            this.$store.state.loadding = true
            tokenPost(tokenLink.cart.delete, info).then(re => {
              this.$store.state.loadding = false
              if (re.status === 0) {
                this.$Message.success('删除成功')
                this._checkShoppingCart()
              } else {
                this.$Message.error(re.msg)
              }
            })
          }
        })
      },
      //跳转到订单页
      _goOrder() {
        let count = this._getGoods()
        if (count.length === 0) {
          this.$Message.info('您还没选择商品呦~')
          return
        }
        let arr = []
        count.forEach(item => {
          arr.push(item.id)
        })
        this.$store.state.orderId = arr.join(',')
        this.$router.push('/Order')
      },
      //获得选择的商品
      _getGoods() {
        let count = []
        let len = []
        this.foodData.forEach(item => {
          len = item.foods.filter(i => {
            return i.sonCheck === true
          })
          len.forEach(item => {
            count.push(item)
          })
        })
        return count
      },
      //查询购物车列表
      _checkShoppingCart() {
        if (window.localStorage.getItem('userId') === null) {
          console.log(22)
          return
        }
        let cart = {
          userId: window.localStorage.getItem('userId'),
        }
        this.$store.state.loadding = true
        tokenPost(tokenLink.cart.checkList, cart).then(re => {
          this.$store.state.loadding = false
          if (re.status === 0) {
            if (re.data.length !== 0) {
              this.cartList = false
            } else {
              this.cartList = true
            }
            this.foodData = this._manageShoppingCartList(re.data)
          } else {
            this.$Message.error(re.msg)
          }
        })
      },
      //购物车列表数据处理
      _manageShoppingCartList(list) {
        let arr = []
        list.forEach(item => {
          let obj = {}
          for (let key in item) {
            obj['shopName'] = item[key][0].businessName
            obj['check'] = false
            item[key].forEach(i => {
              i['sonCheck'] = false
            })
            obj['foods'] = item[key]
          }
          arr.push(obj)
        })
        return arr
      },
    },
    mounted() {
      this.WTITLE('购物车')
      this.RBACK(false)
      this._checkShoppingCart()
    },
    watch: {
      foodData: {
        handler() {
          this._countTotal
        },
        deep: true,
      },
    },
  }
</script>

<style scoped>
  .shopping-cart {
    width: 100%;
    height: 100%;
    padding-top: 45px;
    overflow: auto;
    background: #f6f6f6;
  }

  .shopping-cart .shopping-wrapper {
    width: 100%;
    padding-bottom: 45px;
  }

  .shopping-cart .shopping-wrapper .cartNull {
    padding: 20px 0 ;
    text-align: center;
  }

  .shopping-cart .shopping-wrapper .shopping-item {
    padding: 0 8px 25px;
    margin-bottom: 10px;
    background: #ffffff;
  }

  .shopping-cart .shopping-wrapper .shopping-item .shopping-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 45px;
    border-bottom: 1px solid RGBA(148, 147, 147, 0.2);
    font-size: 0;
  }

  .shopping-cart .shopping-wrapper .shopping-item .shopping-head .sh-icon {
    padding: 0 7px;
  }

  .shopping-cart .shopping-wrapper .shopping-item .shopping-head .name {
    font-size: 13px;
    color: #202020;
  }

  .shopping-cart .shopping-wrapper .shopping-item .shopping-head .sh-right {
    margin-right: 7px;
    font-size: 12px;
    color: #656565;
  }

  .shopping-cart .shopping-wrapper .shopping-item .l-item {
    display: flex;
    align-items: center;
    padding-top: 13px;
    font-size: 0;
  }

  .shopping-cart .shopping-wrapper .shopping-item .l-check {
    padding: 0 10px 0 6px;
  }

  .shopping-cart .shopping-wrapper .shopping-item .l-img {
    border: 1px solid #cfcfcf;
    font-size: 0;
  }

  .shopping-cart .shopping-wrapper .shopping-item .l-desc {
    flex: 1;
    padding-left: 10px;
    vertical-align: top;
  }

  .shopping-cart .shopping-wrapper .shopping-item .l-desc .l-name {
    font-size: 13px;
    color: #202020;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .shopping-cart .shopping-wrapper .shopping-item .l-desc .num {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 10px;
    margin-top: 13px;
  }

  .shopping-cart .shopping-wrapper .shopping-item .l-desc .num .price {
    font-size: 12px;
    color: #a40509;
  }

  .shopping-cart .shopping-bottom {
    position: fixed;
    display: flex;
    bottom: 45px;
    left: 0;
    width: 100%;
    height: 45px;
    background: #f6f6f6;
  }

  .shopping-cart .shopping-bottom .shopping-select {
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: space-between;
    padding: 0 10px 0 15px;
    border-top: 1px solid #d7d7d7;
  }

  .shopping-cart .shopping-bottom .shopping-select .left {
    font-size: 0;
  }

  .shopping-cart .shopping-bottom .shopping-select .left > span {
    margin-left: 10px;
    font-size: 13px;
    color: #202020;
  }

  .shopping-cart .shopping-bottom .shopping-select .right {
    font-size: 12px;
    color: #202020;
  }

  .shopping-cart .shopping-bottom .shopping-select .right .price {
    color: #b30707;
  }

  .shopping-cart .shopping-bottom .shopping-select .deleted {
    display: flex;
  }

  .shopping-cart .shopping-bottom .shopping-select .deleted .delete {
    border: 1px solid red;
    padding: 3px 15px;
    margin-left: 20px;
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    border-radius: 30px;
    color: red;
  }

  .shopping-cart .shopping-bottom .shopping-balance {
    flex: 0 0 111px;
    width: 111px;
    line-height: 45px;
    transform: scale(1);
    transform-origin: 0% 0%;
    background: #fc414e;
    color: #ffffff;
    font-size: 16px;
    font-weight: bold;
    text-align: center;
  }

  .cart-iocn {
    font-size: 25px;
  }
</style>
